import { defineStore } from 'pinia'
import StorageUtil from '../utils/storage'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    rowid: null,
    isLogin: false
  }),

  getters: {
    // 获取用户ID (现在使用rowid)
    userId: (state) => state.rowid,
    
    // 获取用户名
    username: (state) => state.userInfo?.username,
    
    // 获取用户头像
    avatar: (state) => state.userInfo?.avatar,
    
    // 检查是否已登录
    hasLogin: (state) => state.isLogin && !!state.rowid
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLogin = true
      StorageUtil.set('userInfo', userInfo)
    },

    // 设置rowid
    setRowid(rowid) {
      this.rowid = rowid
      StorageUtil.set('rowid', rowid, 7 * 24 * 60 * 60) // 7天过期
    },

    // 登录
    login(userInfo, rowid) {
      this.setUserInfo(userInfo)
      this.setRowid(rowid)
    },

    // 登出
    logout() {
      this.userInfo = null
      this.rowid = null
      this.isLogin = false
      StorageUtil.remove('userInfo')
      StorageUtil.remove('rowid')
    },

    // 初始化用户状态（从本地存储恢复）
    initUserState() {
      const userInfo = StorageUtil.get('userInfo')
      const rowid = StorageUtil.get('rowid')
      
      if (userInfo && rowid) {
        this.userInfo = userInfo
        this.rowid = rowid
        this.isLogin = true
      }
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      StorageUtil.set('userInfo', this.userInfo)
    }
  }
}) 